package com.forlove.app.qselect.index.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.StatusBarCompat;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.recyview.EndLessOnScrollListener;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadUserinfoAsync;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.index.adapter.DetailRankAdapter;
import com.forlove.app.qselect.index.entity.PageEntity;
import com.forlove.app.qselect.index.entity.RankEntity;
import com.forlove.app.qselect.index.presenter.MineInfoPresenter;
import com.forlove.app.qselect.index.view.MineInfoView;
import com.forlove.app.qselect.login.entity.DataDto;
import com.forlove.app.qselect.login.entity.DataInfoEntity;
import com.forlove.app.qselect.login.entity.EmotionEntity;
import com.forlove.app.qselect.login.entity.GroupEntity;
import com.forlove.app.qselect.login.entity.ProvinceEntity;
import com.forlove.app.qselect.login.entity.SchoolDto;
import com.forlove.app.qselect.login.entity.SchoolInfoEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.widget.ResetPwTipDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 我详细页面和好友详情页
 * Created by yjl on 2017/10/11.
 */

public class MineInfoActivity extends BaseActivity implements MineInfoView,
        LoaderManager.LoaderCallbacks<DataDto>, View.OnClickListener {
    public static final int TO_EDITOR_MINE_INFO = 3000; //去设置信息
    public static final int RESULT_SUCCESS_PHOTO = 30001;//  头像设置成功
    public static final int RESULT_SUCCESS_INFO = 30002;// 信息更新成功
    public static final int RESULT_SUCCESS_ACCOUNT = 30003; //账号设置成功
    @BindView(R.id.mine_friend_hot_list)
    RecyclerView friendHotRecycler;

    @BindView(R.id.mine_toolbar)
    Toolbar toolbar;

    @BindView(R.id.text_set)
    TextView text_set;

    @BindView(R.id.user_photo)
    ImageView user_photo; //用户头像

    @BindView(R.id.text_user_name)
    TextView text_user_name;

    @BindView(R.id.image_user_sex)
    AppCompatImageView image_user_sex;

    @BindView(R.id.text_friend_num)
    TextView text_friend_num;

    @BindView(R.id.text_circle_num)
    TextView text_circle_num;

    @BindView(R.id.text_has_circle_num)
    TextView text_has_circle_num;

    @BindView(R.id.view_is_friend)
    LinearLayout view_is_friend;

    @BindView(R.id.text_account_name)
    TextView text_account_name;  //账号

    @BindView(R.id.view_user_id)
    LinearLayout view_user_id;//用户id view

    @BindView(R.id.text_user_msg)
    TextView text_user_msg;

    @BindView(R.id.text_user_proof)
    TextView text_user_proof;

    @BindView(R.id.image_arrow_right)
    ImageView image_arrow_right;

    @BindView(R.id.view_user_msg)
    ConstraintLayout view_user_msg;

    private MineInfoPresenter mineInfoPresenter;
    private String personMobile = "";
    private DetailRankAdapter detailRankAdapter;
    private List<RankEntity> rankEntities = new ArrayList<>();
    private boolean isloadingMore = false;//是否正在加载更多
    private PageEntity pageEntity;

    private UserEntity peopleEntity;  //当前显示的信息
    private UserEntity localUser;//当前登录账户好友
    private boolean showFriend = false;
    private ResetPwTipDialog resetPwTipDialog;
    private LoadUserinfoAsync loadUserinfoAsync;//加载信息
    private List<EmotionEntity> emotionEntities = new ArrayList<>();
    private List<ProvinceEntity> provinceEntities = new ArrayList<>();
    private List<GroupEntity> groupEntities = new ArrayList<>();
    private Map<Integer, SchoolInfoEntity> schoolMap = new HashMap<>();
    private Handler loadSchoollHandler;
    private HandlerThread handlerThread;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_hotlist;
    }

    @Override
    public void initView() {
        mineInfoPresenter = new MineInfoPresenter(this);
        setPresenter(mineInfoPresenter);
        getSupportLoaderManager().restartLoader(LoadUserinfoAsync.ASYNC_ID, null, this);
        loadSchoolCache();
        initData();
        showView();
    }

    private void loadSchoolCache() {
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadSchool");
            handlerThread.start();
        }
        if (loadSchoollHandler == null) {
            loadSchoollHandler = new Handler(handlerThread.getLooper());
        }
        loadSchoollHandler.post(new Runnable() {
            @Override
            public void run() {
                String school = DataManager.getSchoolInfo();
                if (StringUtils.isNotEmpty(school)) {
                    SchoolDto schoolDto = JSON.parseObject(school, SchoolDto.class);
                    if (schoolDto != null && schoolDto.getData() != null) {
                        schoolMap.clear();
                        schoolMap.putAll(schoolDto.getData());
                    }
                }
                mineInfoPresenter.loadSchoolInfo();
            }
        });
    }

    private LoadUserinfoAsync createUserinfoAsync() {
        if (loadUserinfoAsync == null) {
            loadUserinfoAsync = new LoadUserinfoAsync(this);
        }
        return loadUserinfoAsync;
    }

    private void showView() {
        showToolBar(this, toolbar, R.mipmap.ic_back_nor, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        }, null);

        if (showFriend) {
            toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.menu_delete:
                            if (resetPwTipDialog == null) {
                                resetPwTipDialog = new ResetPwTipDialog(MineInfoActivity.this);
                            }
                            resetPwTipDialog.setTextMesseage("是否要删除好友？");
                            resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    requesetDeleteFriend();
                                    resetPwTipDialog.dismiss();
                                }
                            });
                            resetPwTipDialog.show();
                            break;
                        case R.id.menu_report:
                            if (resetPwTipDialog == null) {
                                resetPwTipDialog = new ResetPwTipDialog(MineInfoActivity.this);
                            }
                            resetPwTipDialog.setTextMesseage("是否要举报好友？");
                            resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    requestReportFriend();
                                    resetPwTipDialog.dismiss();
                                }
                            });

                            resetPwTipDialog.show();
                            break;
                    }
                    return false;
                }
            });
        }
        text_set.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (showFriend) {
            getMenuInflater().inflate(R.menu.menu_friend_info, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    private void initData() {
        Intent intent = getIntent();
        String mobile = intent.getStringExtra("mobile");
        localUser = UserManager.getUesrInfo(this);
        if (!TextUtils.isEmpty(mobile)) {
            personMobile = mobile;
            if (!TextUtils.isEmpty(personMobile) && personMobile.equals(localUser.userMobile)) {
                //自己的信息
                text_set.setVisibility(View.VISIBLE);
                showFriend = false;
                image_arrow_right.setVisibility(View.VISIBLE);
                view_user_msg.setOnClickListener(this);
            } else {
                //TODO 好友信息
                showFriend = true;
                image_arrow_right.setVisibility(View.GONE);
                text_set.setVisibility(View.INVISIBLE);
                view_user_msg.setOnClickListener(null);
            }
        } else {
            //显示自己信息
            personMobile = localUser.userMobile;
            text_set.setVisibility(View.VISIBLE);
            image_arrow_right.setVisibility(View.VISIBLE);
            view_user_msg.setOnClickListener(this);
        }
        if (TextUtils.isEmpty(personMobile) || personMobile.equals(localUser.userMobile)) {
            showUserInfoView(localUser);
        }
        detailRankAdapter = new DetailRankAdapter(this, R.layout.item_detail_rank, rankEntities, mineInfoPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        friendHotRecycler.setLayoutManager(linearLayoutManager);
        friendHotRecycler.setAdapter(detailRankAdapter);
        detailRankAdapter.updateDatas(rankEntities);
        detailRankAdapter.hideFooterView();
        detailRankAdapter.hideEmptyView();
        friendHotRecycler.addOnScrollListener(new EndLessOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                if (!isloadingMore) {
                    isloadingMore = true;
                    detailRankAdapter.showFootLoading();
                    requestMoreRank();
                    if (mHandler == null) {
                        mHandler = new Handler();
                    }
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            detailRankAdapter.hideFooterView();
                            isloadingMore = false;
                        }
                    }, 6000);
                }
            }
        });
        requestDetailInfo();
        requestRankList();
    }

    private void showUserInfoView(UserEntity userEntity) {
        if (userEntity == null) {
            return;
        }
        mineInfoPresenter.loadImageView(this, user_photo,
                userEntity.mUserImage, R.mipmap.image_mine_friend_avatar);
        text_user_name.setText(userEntity.realname);
        if (userEntity.mSex == 1) {
            image_user_sex.setBackground(getResources().getDrawable(R.mipmap.image_mine_boy));
        } else if (userEntity.mSex == 2) {
            image_user_sex.setBackground(getResources().getDrawable(R.mipmap.image_mine_girl));
        }
        text_friend_num.setText(userEntity.friends_count + "");
        text_circle_num.setText(userEntity.note_times + "");
        text_has_circle_num.setText(userEntity.answer_times + "");
        if (userEntity.isfriend && !this.localUser.userMobile.equals(userEntity.userMobile)) {
            view_is_friend.setVisibility(View.VISIBLE);
        } else {
            view_is_friend.setVisibility(View.INVISIBLE);
        }
        if (StringUtils.isNotEmpty(userEntity.userName)) {
            text_account_name.setText(userEntity.userName);
//            text_account_name.setVisibility(View.VISIBLE);
            view_user_id.setVisibility(View.VISIBLE);
        } else {
//            text_account_name.setVisibility(View.GONE);
            view_user_id.setVisibility(View.GONE);
        }
        if (emotionEntities.size() > 0 && provinceEntities.size() > 0) {
            showPeopleMsg(userEntity);
        }

        if (schoolMap != null) {
            showSchoolInfo(userEntity);
        }
    }

    private void showPeopleMsg(UserEntity userEntity) {
        StringBuilder stringBuilder = new StringBuilder();
        if (userEntity.mSex == 1) {
            stringBuilder.append("男").append("  ");
        } else if (userEntity.mSex == 2) {
            stringBuilder.append("女").append("  ");
        }
        if (userEntity.issingle > 0 && emotionEntities.size() > 0) {
            EmotionEntity parentEmotion = null;
            DataInfoEntity childEmotion = null;
            for (EmotionEntity emotionEntity : emotionEntities) {
                childEmotion = emotionEntity.getChildEmotion(userEntity.issingle);
                if (childEmotion != null) {
                    parentEmotion = emotionEntity;
                    break;
                }
            }
            if (parentEmotion != null) {
                stringBuilder.append(parentEmotion.emotion.getName() + "").append("  ");
            }
        }
        if (StringUtils.isNotEmpty(userEntity.birthday)
                && !"0".equals(userEntity.birthday)) {
            int years = MyTimeUtils.getYearsNum(System.currentTimeMillis());
            int birthday = MyTimeUtils.getBirthYear(userEntity.birthday);
            int age = (years - birthday);
            if (age < 100) {
                stringBuilder.append(age + "岁").append("  ");
            }
        }
        if (userEntity.address > 0 && provinceEntities.size() > 0) {
            ProvinceEntity province = null;
            DataInfoEntity city = null;
            for (ProvinceEntity provinceEntity : provinceEntities) {
                city = provinceEntity.getCity(userEntity.address);
                if (city != null) {
                    province = provinceEntity;
                    break;
                }
            }
            if (province != null) {
                stringBuilder.append(province.province.getName() + "").append(" - ");
            }
            if (city != null) {
                stringBuilder.append(city.getName() + "  ");
            }
        }
        if (stringBuilder.length() > 0) {
            text_user_msg.setText(stringBuilder.toString());
        } else {
            text_user_msg.setVisibility(View.GONE);
        }
    }

    private void showSchoolInfo(UserEntity userEntity) {
        if (userEntity == null || schoolMap.isEmpty()) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (userEntity.school > 0
                && userEntity.scholar >= 10100
                && userEntity.scholar <= 10109) {
            SchoolInfoEntity schoolInfoEntity = schoolMap.get(userEntity.school);
            if (schoolInfoEntity != null) {
                stringBuilder.append(schoolInfoEntity.school);
            }

            if (StringUtils.isNotEmpty(userEntity.yuanxi)) {
                if (stringBuilder.length() > 0) {
                    stringBuilder.append(" - ");
                }
                stringBuilder.append(userEntity.yuanxi);
            }
            text_user_proof.setText(stringBuilder.toString());
            text_user_proof.setVisibility(View.VISIBLE);
        } else {
            if (userEntity.scholar > 0) {
                for (GroupEntity groupEntity : groupEntities) {
                    DataInfoEntity childGroup = groupEntity.getChildGroup(userEntity.scholar);
                    if (childGroup != null) {
                        stringBuilder.append(groupEntity.mGroup.getName());
                        if (userEntity.scholar < 10300) {
                            //不是工作党显示年级
                            stringBuilder.append(" - ").append(childGroup.getName());
                        }
                        text_user_proof.setText(stringBuilder.toString());
                        text_user_proof.setVisibility(View.VISIBLE);
                        break;
                    }
                }

            } else {
                text_user_proof.setVisibility(View.GONE);
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        StatusBarCompat.compat(this, Color.parseColor("#2ac2b9"));
    }

    private void requestDetailInfo() {
        Map param = new HashMap();
        param.put("mobile", personMobile);
        mineInfoPresenter.loadDetailData(param);
    }

    private void requestRankList() {
        if (pageEntity == null) {
            pageEntity = new PageEntity();
        }
        pageEntity.mPage = 1;
        pageEntity.mobile = personMobile;
        mineInfoPresenter.loadRankingList(pageEntity);
    }

    private void requestMoreRank() {
        if (pageEntity == null) {
            pageEntity = new PageEntity();
        }
        pageEntity.mobile = personMobile;
        mineInfoPresenter.loadMoreRankList(pageEntity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_user_msg:
                Intent intent = new Intent(this, ChangeMineInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userEntity", localUser);
                intent.putExtras(bundle);
//                startActivity(intent);
                startActivityForResult(intent, TO_EDITOR_MINE_INFO);
                break;
            case R.id.text_set:
                startActivity(new Intent(MineInfoActivity.this, SetActivitty.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("yjl", "requestCode:" + requestCode + "   resultCode:" + resultCode);
        if (requestCode == TO_EDITOR_MINE_INFO) {
            switch (resultCode) {
                case RESULT_SUCCESS_PHOTO:
                    mineInfoPresenter.loadImageView(this, user_photo,
                            localUser.mUserImage, R.mipmap.image_mine_friend_avatar);
                case RESULT_SUCCESS_INFO:
                case RESULT_SUCCESS_ACCOUNT:
                    requestDetailInfo();
                    break;
            }
        }
    }

    @Override
    public void updateMineInfo(final UserEntity userEntity) {
        showUserInfoView(userEntity);
        peopleEntity = userEntity;
        if (peopleEntity.userMobile.equals(localUser.userMobile)) {
            localUser.updateUserEntity(userEntity);
            UserManager.saveUserInfo(this, localUser);
        }
    }

    @Override
    public void updataRanklistView(PageEntity pageEntity, final List<RankEntity> rankEntities) {
        this.pageEntity = pageEntity;
        isloadingMore = false;
        detailRankAdapter.hideFooterView();
        detailRankAdapter.updateDatas(rankEntities);
    }

    private void requesetDeleteFriend() {
        Map param = new HashMap();
        param.put("friend", personMobile);
        mineInfoPresenter.loadDeleteFirend(param);
    }

    private void requestReportFriend() {
        Map param = new HashMap();
        param.put("friend", personMobile);
        mineInfoPresenter.loadReportFriend(param);
    }

    @Override
    public Loader<DataDto> onCreateLoader(int id, Bundle args) {
        return createUserinfoAsync();
    }

    @Override
    public void onLoadFinished(Loader<DataDto> loader, DataDto data) {
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (data != null) {
            emotionEntities.addAll(DataManager.parseEmotion(data.getEmotion()));
            provinceEntities.addAll(DataManager.parseCityData(data.getCitys()));
            groupEntities.addAll(DataManager.parseGroupData(data.getGroup()));
            if (peopleEntity != null) {
                showPeopleMsg(peopleEntity);
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<DataDto> loader) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (handlerThread != null) {
            handlerThread.quitSafely();
            handlerThread = null;
        }
        if (loadSchoollHandler != null) {
            loadSchoollHandler.removeCallbacksAndMessages(null);
            loadSchoollHandler = null;
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        isloadingMore = false;
    }

    @Override
    public void updateDelteView(CommonEntity commonEntity) {
        //删除好友
        Toast.makeText(this, "删除成功!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateReportView(CommonEntity commonEntity) {
        //举报好友
        Toast.makeText(this, "举报成功!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateSchoolInfo(Map<Integer, SchoolInfoEntity> school) {
        if (school != null && !school.isEmpty()) {
            this.schoolMap.clear();
            this.schoolMap.putAll(school);
            if (peopleEntity != null) {
                showSchoolInfo(peopleEntity);
            }
        }

    }
}
